import { z } from "zod";
import { codeartsrepoRequest, buildUrl } from "../common/utils.js";
import { RepositorySchema } from "../common/types.js";

// 获取一个项目下可以设置为公开状态的仓库列表
export const ListProductTwoTemplatesSchema = z.object({
  project_id: z.string().describe("项目ID"),
});

// 校验指定项目下的仓库名
export const ShowRepositoryNameExistSchema = z.object({
  project_id: z.string().describe("项目ID"),
  repo_name: z.string().describe("仓库名"),
});

// 功能实现
export async function listProductTwoTemplates(
  projectId: string
) {
  const url = `https://codeartsrepo.example.com/api/v2/projects/${projectId}/public_repos`;
  const response = await codeartsrepoRequest(url);
  return z.array(RepositorySchema).parse(response);
}

export async function showRepositoryNameExist(
  projectId: string,
  repoName: string
) {
  const url = buildUrl(`https://codeartsrepo.example.com/api/v2/projects/${projectId}/repository/name_exists`, {
    repo_name: repoName
  });

  const response = await codeartsrepoRequest(url);
  return z.object({
    exists: z.boolean()
  }).parse(response);
}

// 获取项目详情
export async function getProject(
  projectId: string
) {
  const url = `https://codeartsrepo.example.com/api/v2/projects/${projectId}`;
  const response = await codeartsrepoRequest(url);
  
  return z.object({
    id: z.string(),
    name: z.string(),
    description: z.string().optional(),
    visibility: z.enum(["private", "public"]),
    created_at: z.string(),
    updated_at: z.string(),
    owner: z.object({
      id: z.string(),
      name: z.string(),
      email: z.string().optional(),
      avatar_url: z.string().optional(),
    }),
    web_url: z.string(),
  }).parse(response);
}

// 创建项目
export async function createProject(
  name: string,
  options?: {
    description?: string;
    visibility?: "private" | "public";
  }
) {
  const response = await codeartsrepoRequest("https://codeartsrepo.example.com/api/v2/projects", {
    method: "POST",
    body: {
      name,
      description: options?.description,
      visibility: options?.visibility || "private"
    }
  });
  
  return z.object({
    id: z.string(),
    name: z.string(),
    description: z.string().optional(),
    visibility: z.enum(["private", "public"]),
    created_at: z.string(),
    updated_at: z.string(),
    owner: z.object({
      id: z.string(),
      name: z.string(),
      email: z.string().optional(),
      avatar_url: z.string().optional(),
    }),
    web_url: z.string(),
  }).parse(response);
} 